﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

namespace CoNatural.Data.VisualStudio.AddIn.Controls {
   public partial class SelectStoredProceduresControl : UserControl {
      private string connectionString;

      public SelectStoredProceduresControl() {
         InitializeComponent();
      }

      public void Initialize(string connectionString) {
         this.connectionString = connectionString;
         dbObjectBindingSource.Clear();
      }

      public IList<Model.DbObject> GetSelection() {
         IList<Model.DbObject> selection = new List<Model.DbObject>();

         foreach (Model.DbObject sp in dbObjectBindingSource)
            if(sp.Selected)
               selection.Add(sp);

         return selection;
      }

      private void refreshButton_Click(object sender, EventArgs e) {
         Server server = new Server(new ServerConnection(new System.Data.SqlClient.SqlConnection(connectionString)));
         Database db = server.Databases[server.ConnectionContext.DatabaseName];
         List<Model.DbObject> sps = new List<CoNatural.Data.VisualStudio.AddIn.Model.DbObject>();
         foreach (StoredProcedure sp in db.StoredProcedures) {
				if (schemaTextBox.Text.Trim().Length > 0 && !sp.Schema.Equals(schemaTextBox.Text.Trim(), StringComparison.OrdinalIgnoreCase))
					continue;
				if (prefixTextBox.Text.Trim().Length > 0 && !sp.Name.StartsWith(prefixTextBox.Text.Trim(), StringComparison.OrdinalIgnoreCase))
					continue;
				sps.Add(new CoNatural.Data.VisualStudio.AddIn.Model.DbObject(sp.Schema, sp.Name));
         }
         dbObjectBindingSource.DataSource = sps;
      }

      private void selectAllButton_Click(object sender, EventArgs e) {
         foreach (Model.DbObject sp in dbObjectBindingSource)
            sp.Selected = true;
         dataGrid.Refresh();
      }

      private void clearAllButton_Click(object sender, EventArgs e) {
         foreach (Model.DbObject sp in dbObjectBindingSource)
            sp.Selected = false;
         dataGrid.Refresh();
      }
   }
}
